﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SqlServer.Dts.Runtime;
using Microsoft.SqlServer.Dts.Runtime.Design;
using Microsoft.SqlServer.Management.Smo;

namespace SSISTransferLoginsTask
{
    public partial class CopyLoginsForm : Form
    {
        private TaskHost _TaskHost;
        private IServiceProvider _ServiceProvider;
        private HashSet<String> _SelectedLoginsDatabases;
        public CopyLoginsForm(TaskHost taskHost,IServiceProvider serviceProvider)
        {
            InitializeComponent();

            _TaskHost = taskHost;
            _ServiceProvider = serviceProvider;

            if (taskHost != null)
            {
                // Fill in the form based on the existing properties of the task
                // Retrieve the CopyLoginsTask and list of connection managers from the
                // task wrapper
                CopyLoginsTask task=(CopyLoginsTask) _TaskHost.InnerObject;
                Connections connections = task.Connections;
                // Use the CopyLoginsTask to fill in the Editor form
                // Fill up the list of connections
                if (connections != null)
                {
                    foreach (var conMgr in connections)
                    {
                        if (conMgr.CreationName == "SMOServer")
                        {
                            comboBoxSourceInstance.Items.Add(conMgr.Name);
                            comboBoxdestinationInstance.Items.Add(conMgr.Name);
                        }
                    }
                }
                // Fill in the name of the task
                textBoxName.Text = _TaskHost.Name;
                // Fill in the description of the task
                textBoxDescription.Text = _TaskHost.Description;
                // Fill in the Source and Destination connection
                if (task.SourceConnection != null)
                    comboBoxSourceInstance.Text = task.SourceConnection.Name;
                if (task.DestinationConnection != null)
                    comboBoxdestinationInstance.Text = task.DestinationConnection.Name;
                // Fill in the LoginsTransferred
                //   List the databases or logins that where selected
                _SelectedLoginsDatabases = new HashSet<string>(task.SelectedLoginsDatabases);
                switch (task.LoginsTransferred)
                {
                    case LoginsTransferred.AllLogins:
                        comboBoxLoginsToTransfer.SelectedIndex = 0;
                        break;
                    case LoginsTransferred.SelectedLogins:
                        comboBoxLoginsToTransfer.SelectedIndex = 1;
                        break;
                    default:
                        comboBoxLoginsToTransfer.SelectedIndex = 2;
                        break;
                }
                // Empty the list of databases that where selected
                _SelectedLoginsDatabases.Clear();
                // Fill in the IfObjectExists
                switch (task.IfObjectExists)
                {
                    case IfObjectExists.Skipp:
                        comboBoxIfObjectsExists.SelectedIndex = 0;
                        break;
                    case IfObjectExists.Overwrite:
                        comboBoxIfObjectsExists.SelectedIndex = 1;
                        break;
                    default:
                        comboBoxIfObjectsExists.SelectedIndex=2;
                        break;
                }
                // Fill in the CopySID
                checkBoxCopySID.Checked = task.CopySID;
                // Fill in the CopyPassword
                checkBoxCopyPassword.Checked = task.CopyPassword; 
                // Fill in the StopOnError
                checkBoxStopOnError.Checked = task.StopOnError;
            }
        }

        /*
         * Create a new connection MGR
         */
        private string CreateConnectionMgr()
        {
            try
            {
                IDtsConnectionService connService = (IDtsConnectionService)_ServiceProvider.GetService(typeof(IDtsConnectionService));
                ArrayList conns = connService.CreateConnection("SMOServer");
                String connMgrName=null;
                foreach (ConnectionManager connMgr in conns)
                {
                    connMgrName = connMgr.Name;
                    comboBoxSourceInstance.Items.Add(connMgrName);
                    comboBoxdestinationInstance.Items.Add(connMgrName);
                };
                return connMgrName;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
        }

        private void comboBoxSourceInstance_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (comboBoxSourceInstance.SelectedIndex == 0)
                {
                    // We must create a new connection manager
                    string mgrName = CreateConnectionMgr();
                    if (mgrName != null)
                    {
                        comboBoxSourceInstance.Text = mgrName;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.StackTrace);
            }
        }
        private void comboBoxDestinationInstance_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (comboBoxdestinationInstance.SelectedIndex == 0)
                {
                    // We must create a new connection manager
                    string mgrName = CreateConnectionMgr();
                    if (mgrName != null)
                    {
                        comboBoxdestinationInstance.Text = mgrName;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.StackTrace);
            }
        }

        private void buttonOk_Click(object sender, EventArgs e)
        {
            try
            {
                if (_TaskHost != null)
                {
                    Connections connections = ((CopyLoginsTask)_TaskHost.InnerObject).Connections;
                    ConnectionManager mgr;
                    if (connections.Contains(comboBoxSourceInstance.Text) &&
                        (mgr=connections[comboBoxSourceInstance.Text])!= null)
                    {
                        _TaskHost.Properties["SourceConnection"].SetValue(_TaskHost, mgr);
                    };
                    if (connections.Contains(comboBoxdestinationInstance.Text) &&
                        (mgr=connections[comboBoxdestinationInstance.Text])!= null)
                    {
                        _TaskHost.Properties["DestinationConnection"].SetValue(_TaskHost, mgr);
                    }
                    switch (comboBoxLoginsToTransfer.SelectedIndex)
                    {
                        case 0: // All Logins
                            _TaskHost.Properties["LoginsTransferred"].SetValue(_TaskHost, LoginsTransferred.AllLogins);
                            break;
                        case 1: // Selected Logins
                            _TaskHost.Properties["LoginsTransferred"].SetValue(_TaskHost, LoginsTransferred.SelectedLogins);
                            break;
                        default: // Selected Databases
                            _TaskHost.Properties["LoginsTransferred"].SetValue(_TaskHost, LoginsTransferred.SelectedDatabases);
                            break;
                    }
                    switch (comboBoxIfObjectsExists.SelectedIndex)
                    {
                        case 0: // Skipp transfer
                            _TaskHost.Properties["IfObjectExists"].SetValue(_TaskHost, IfObjectExists.Skipp);
                            break;
                        case 1: // Overwrite
                            _TaskHost.Properties["IfObjectExists"].SetValue(_TaskHost, IfObjectExists.Overwrite);
                            break;
                        default: // Fail
                            _TaskHost.Properties["IfObjectExists"].SetValue(_TaskHost, IfObjectExists.Fail);
                            break;
                    }
                    _TaskHost.Properties["CopySID"].SetValue(_TaskHost, checkBoxCopySID.Checked);
                    _TaskHost.Properties["CopyPassword"].SetValue(_TaskHost, checkBoxCopyPassword.Checked);
                    _TaskHost.Properties["StopOnError"].SetValue(_TaskHost, checkBoxStopOnError.Checked);
                    string[] selectedLoginsDatabases=new string[checkedListBoxLoginsDatabases.CheckedItems.Count];
                    for (int i=0;i<selectedLoginsDatabases.Length;i++)
                        selectedLoginsDatabases[i]=(string) checkedListBoxLoginsDatabases.CheckedItems[i];
                    _TaskHost.Properties["SelectedLoginsDatabases"].SetValue(_TaskHost,selectedLoginsDatabases);
                    _TaskHost.Name = textBoxName.Text;
                    _TaskHost.Description = textBoxDescription.Text;
                    DialogResult = DialogResult.OK;
                    Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.StackTrace);
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        private void comboBoxLoginsToTransfer_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (comboBoxLoginsToTransfer.SelectedIndex)
            {
                case 0:
                    // All Logins
                    labelLoginsDatabase.Text="All Logins";
                    checkedListBoxLoginsDatabases.Enabled = false;
                    break;
                case 1:
                    // Selected Logins
                    labelLoginsDatabase.Text = "Selected Logins";
                    checkedListBoxLoginsDatabases.Enabled = true;
                    fillInLogins();
                    break;
                default:
                    // Selected Databases
                    labelLoginsDatabase.Text = "Selected Databases";
                    checkedListBoxLoginsDatabases.Enabled = true;
                    fillInDatabases();
                    break;
            }
        }
        private void fillInLogins()
        {
            if (_TaskHost != null)
            {
                if (comboBoxSourceInstance.SelectedIndex == 0)
                {
                    // Can not provide a connection
                    MessageBox.Show("No source connection filled in");
                }
                else
                {
                    CopyLoginsTask task = (CopyLoginsTask)_TaskHost.InnerObject;
                    ConnectionManager connMgr = task.Connections[comboBoxSourceInstance.Text];
                    Server server = (Server) connMgr.AcquireConnection(null);
                    checkedListBoxLoginsDatabases.Items.Clear();
                    foreach (Login login in server.Logins)
                    {
                        checkedListBoxLoginsDatabases.Items.Add(login.Name,_SelectedLoginsDatabases.Contains(login.Name));
                    }
                }
            }
        }
        private void fillInDatabases()
        {
            if (_TaskHost != null)
            {
                if (comboBoxSourceInstance.SelectedIndex == 0)
                {
                    // Can not provide a connection
                    MessageBox.Show("No source connection filled in");
                }
                else
                {
                    CopyLoginsTask task = (CopyLoginsTask)_TaskHost.InnerObject;
                    ConnectionManager connMgr = task.Connections[comboBoxSourceInstance.Text];
                    Server server = (Server)connMgr.AcquireConnection(null);
                    checkedListBoxLoginsDatabases.Items.Clear();
                    foreach (Database db in server.Databases)
                    {
                        checkedListBoxLoginsDatabases.Items.Add(db.Name, _SelectedLoginsDatabases.Contains(db.Name));
                    }
                }
            }
        }
    }

}
